package com.example.demo1;

import com.example.demo1.Book;
import com.example.demo1.BookRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class BookService {

    private final BookRepository bookRepository;

    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    // 搜索图书（支持分页）
    public Page<Book> searchBooks(String title, Boolean available, Pageable pageable) {
        if (title != null && available != null) {
            return bookRepository.findByTitleContainingAndAvailable(title, available, pageable);
        } else if (title != null) {
            return bookRepository.findByTitleContaining(title, pageable);
        } else if (available != null) {
            return bookRepository.findByAvailable(available, pageable);
        } else {
            return bookRepository.findAll(pageable);
        }
    }

    // 根据 ID 获取图书
    public Book getBookById(Long id) {
        return bookRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在"));
    }

    // 添加图书
    public Book addBook(Book book) {
        // 检查 ISBN 是否已存在（如果需要唯一性）
        if (book.getIsbn() != null && bookRepository.existsByIsbn(book.getIsbn())) {
            throw new IllegalArgumentException("ISBN 已存在");
        }
        return bookRepository.save(book);
    }

    // 更新图书
    @Transactional
    public Book updateBook(Long id, Book bookDetails) {
        Book book = bookRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在"));

        // 更新非空字段
        if (bookDetails.getTitle() != null) book.setTitle(bookDetails.getTitle());
        if (bookDetails.getAuthor() != null) book.setAuthor(bookDetails.getAuthor());
        if (bookDetails.getPublisher() != null) book.setPublisher(bookDetails.getPublisher());
        if (bookDetails.getIsbn() != null) book.setIsbn(bookDetails.getIsbn());
        if (bookDetails.getAvailable() != null) book.setAvailable(bookDetails.getAvailable());

        return bookRepository.save(book);
    }

    // 删除图书
    public void deleteBook(Long id) {
        if (!bookRepository.existsById(id)) {
            throw new IllegalArgumentException("图书不存在");
        }
        bookRepository.deleteById(id);
    }

    // 借阅图书
    @Transactional
    public void borrowBook(Long bookId) {
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在"));

        if (!book.getAvailable()) {
            throw new IllegalArgumentException("图书已被借出");
        }

        book.setAvailable(false);
        bookRepository.save(book);
    }

    // 归还图书
    @Transactional
    public void returnBook(Long bookId) {
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new IllegalArgumentException("图书不存在"));

        if (book.getAvailable()) {
            throw new IllegalArgumentException("图书未被借出");
        }

        book.setAvailable(true);
        bookRepository.save(book);
    }
}